<template>
  <Modal v-model="status"
         width="1500"
         title="新增发文"
         footer-hide 
         :mask-closable="false">
    <div class="operationBox">
      <div class="operationContent notice_contents">
        <Form label-position="top"
              ref="form"
              :model="noticeItem"
              :rules="rules"
              style="padding:0 10px;">
          <Form-item label="标题"
                     prop="srmsg_title">
            <Input v-model="noticeItem.srmsg_title"
                   :maxlength="200"
                   class="input_new" />
          </Form-item>
          <Form-item label="接收人"
                     prop="receiver_ids">
            <Input v-model="noticeItem.receiver_ids"
                   :maxlength="200"
                   class="input_new"
                   placeholder="请选择"
                   readonly
                   @on-focus="showUserTree" />
          </Form-item>
          <!-- <Form-item label="推送方式"
                     prop="push">
            <CheckboxGroup v-model="noticeItem.push">
              <Checkbox label="app推送"></Checkbox>
            </CheckboxGroup>
          </Form-item> -->
          <Form-item label="任务描述"
                     prop="srmsg_text">
            <div ref="editor"
                 style="text-align:left;z-index: 88"></div>
          </Form-item>
          <Form-item class="upload_file"
                     label="附件"
                     prop="enclosures">
            <Upload :show-upload-list="false"
                    multiple
                    type="drag"
                    :format="['pdf','doc','docx','word','xls','xlsx','jpg','png','jpeg']"
                    :on-format-error="handleFormatError"
                    :on-success="handleSuccess"
                    :max-size="102400"
                    :on-exceeded-size="handleMaxSize"
                    :action="daoruUrl">
              <div>
                <Icon type="ios-cloud-upload"
                      size="23"
                      style="color: #52A1FD;height: 100%;vertical-align: middle;"></Icon>
                <span>上传附件</span>
              </div>
            </Upload>
            <span class="tips">单个文件不能超过100M（支持PDF，Word，Excel，JPG，PNG，JPEG）</span>
          </Form-item>
          <Form-item v-show="noticeItem.enclosures.length > 0"
                     label="附件">
            <div v-for="(item,index) in noticeItem.enclosures"
                 :key="index">
              <a target="_blank"
                 :href="item.path"><img style="margin: 8px 5px 0 0"
                     src="static/img/file.png"
                     alt="">{{item.filename}}</a>
              <i class="ivu-icon ivu-icon-ios-close-circle"
                 style="width:16px;height:16px;color:red;font-size:16px;line-height:16px"
                 @click="delUpload(index)"></i>

            </div>
          </Form-item>
        </Form>
      </div>

      <div slot='footer'>
        <Button type="primary"
                @click="newNotice">保存</Button>
        <Button @click="cancel">取消</Button>
      </div>
      <user-tree ref="JUserTree"
                 @change="setReceiver" />
    </div>
    <Spin v-show="loading"
          ssize="large"
          fix />
  </Modal>
</template>

<script>
import storage from 'good-storage';
import UserTree from '../UserTree';
import EditTools from 'wangeditor';
import { domain } from 'global/setting';
import { ajaxPost } from 'global/axios';
import jquery from 'jquery';

let editor = null;

export default {
  components: {
    'user-tree': UserTree,
  },

  data() {
    return {
      status: false,
      loading: false,
      daoruUrl: '',
      noticeItem: {
        srmsg_text: '',
        srmsg_title: '',
        receiver_ids: '',
        enclosures: [],
        push: [],
      },
      receiverList: [],

      rules: {
        srmsg_title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
        ],
        srmsg_text: [
          { required: true, message: '正文不能为空', trigger: 'blur' },
        ],
        receiver_ids: [
          {
            required: true,
            message: '接受人不能为空',
            trigger: 'change',
          },
        ],
      },
    };
  },

  mounted() {
    this.daoruUrl = `${domain}/filemanage/upload?dir=srmsg&token=${storage.session.get(
      'token'
    )}`;
    editor = new EditTools(this.$refs.editor);
    editor.customConfig.onchange = html => {
      this.noticeItem.srmsg_text = html;
    };
    editor.customConfig.uploadImgShowBase64 = true;
    editor.create();
  },

  methods: {
    show() {
      this.status = true;
    },
    cancel() {
      this.status = false;
      this.noticeItem = {
        srmsg_text: '',
        srmsg_title: '',
        receiver_ids: '',
        enclosures: [],
        push: [],
      };
      editor.$textElem[0].innerHTML = '';
      this.receiverList = [];
      this.$refs.JUserTree.cancel();
    },

    showUserTree() {
      this.$refs.JUserTree.show();
    },

    setReceiver(data) {
      let receiver_ids = [];
      this.receiverList = data.map(item => {
        receiver_ids.push(item.realname);
        return { receiver_name: item.realname, receiver_id: item.userid };
      });
      this.noticeItem.receiver_ids = receiver_ids.join('、');
    },

    handleSuccess(res) {
      this.$Loading.finish();
      this.noticeItem.enclosures.push({
        path: res.result.path,
        filename: res.result.filename,
      });
    },

    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: `文件格式不正确，请上传PDF，Word，Excel，JPG，PNG，JPEG格式的图片。`,
      });
    },

    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: `文件 ${file.name} 太大，不能超过 100M。`,
      });
    },

    delUpload(index) {
      this.noticeItem.enclosures.splice(index, 1);
    },

    newNotice() {
      this.noticeItem.srmsg_text === '<p><br></p>' &&
        (this.noticeItem.srmsg_text = '');
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true;
          // let have_apppush = false;
          // let have_phone = false;
          // if (this.noticeItem.push.length > 0) {
          //   this.noticeItem.push.map(item => {
          //     if (item === '短信推送') {
          //       have_phone = true;
          //     } else if (item === 'app推送') {
          //       have_apppush = true;
          //     }
          //   });
          // }

          let params = {
            data: {
              enclosures: this.noticeItem.enclosures,
              srmsg_title: this.noticeItem.srmsg_title,
              srmsg_text: this.noticeItem.srmsg_text,
              receivers: this.receiverList
            },
            token: storage.session.get('token'),
            url: '/bus/srmsg/new',
            success: res => {
              this.loading = false;
              if (res.data.code == '0000') {
                this.$Message.success({
                  content: '发文成功',
                });
                this.cancel();
                this.$emit('update');
              } else {
                this.$Message.warning({
                  content: res.data.message,
                });
              }
            },
          };
          ajaxPost(params);
        }
      });
    },
  },
};
</script>

<style lang="less" scope>
.upload_file {
  .ivu-form-item-content {
    display: flex;
    .ivu-upload {
      margin-right: 10px;
    }
  }
}
.input_new {
  .ivu-input {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
  }
}
</style>